<?php

namespace App\Module\Sub;

use App\depository\PermissionsDep;
use App\depository\RoleHasPermissionsDep;
use App\depository\RolesDep;
use App\depository\SubPermissionsDep;
use App\depository\SubTeamUserDep;
use App\depository\UserDep;
use App\Enum\CommonEnum;
use App\Enum\PermissionsEnum;
use App\Enum\RolesEnum;
use App\Enum\SubCodeEnum;
use App\Module\BaseModule;
use App\Service\DictService;
use App\depository\SubRolesDep;
use App\depository\SubRoleHasPermissionsDep;
use Illuminate\Support\Str;
use App\depository\SubCodeDep;

class SubCodeModule extends BaseModule
{

    public function init($request)
    {

        $param = $request->input();

        $dictService = new DictService();
        $dictService
            ->setSubCodeStatus();

        $data = [
            'dict' => $dictService->getDict(),
            'default_expire_at' => date('Y-m-d H:i:s', strtotime('+1 day'))
        ];

        return self::response($data);
    }


    public function add($request)
    {
        $param = $request->input();

        $userId = $request->user()->id;
        $teamId = $request->headers->get('TeamId');

        for ($i = 1; $i <= $param['number']; $i++) {
            $origin = $teamId . time() . Str::random(5);
            $code = md5($origin);

            $data = [
                'team_id' => $teamId,
                'code' => $code,
                'expire_at' => $param['expire_at'],
                'status' => SubCodeEnum::STATUS_WAIT,
            ];

            $subCodeDep = new SubCodeDep();
            $subCodeDep->add($data);
        }

        return self::response();
    }

    public function del($request)
    {
        $param = $request->input();

        $dep = new SubCodeDep();

        $dep->del($param['id']);
        return self::response();
    }

    public function edit($request)
    {
        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        if (empty($param['name'])) {
            return self::response([], '请填写标题', 100);
        }

        if (empty($param['guard_name'])) {
            return self::response([], '请填写标识', 100);
        }

        $data = [
            'name' => $param['name'],
            'guard_name' => $param['guard_name'],
            'remark' => $param['remark'] ?? "",
            'status' => $param['status']
        ];

        $dep = new SubRolesDep();
        $dep->upd($param['id'], $data);

        $roleHasPermissionsDep = new SubRoleHasPermissionsDep();
        $roleHasPermissionsDep->delByRoleId($param['id']);

        if (!empty($param['permission_id'])) {
            foreach ($param['permission_id'] as $permissionId) {
                $data = [
                    'team_id' => $teamId,
                    'role_id' => $param['id'],
                    'permission_id' => $permissionId
                ];
                $roleHasPermissionsDep->add($data);
            }
        }

        return self::response();

    }

    public function list($request)
    {
        $param = $request->input();

        $teamId = $request->headers->get('TeamId');

        $userDep = new UserDep();
        $subCodeDep = new SubCodeDep();
        $resList = $subCodeDep->list($teamId, $param);
        $list = $resList->getCollection()->toBase();
        $data['list'] = $list->map(function ($item) use ($userDep) {
            $resUser = $userDep->firstById($item->user_id);
            return [
                'id' => $item->id,
                'code' => $item->code,
                'status' => $item->status,
                'status_show' => isset(SubCodeEnum::$statusArr[$item->status]) ? SubCodeEnum::$statusArr[$item->status] : CommonEnum::DEFAULT_NULL,
                'user_id' => $item->user_id,
                'user_show' => $resUser ? $resUser->name : CommonEnum::DEFAULT_NULL,
                'expire_at' => $item->expire_at,
                'is_expire' => (date('Y-m-d H:i:s') > $item->expire_at) ? true : false,
                'created_at' => $item->created_at->toDateTimeString()
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }

    public function join($request)
    {

        $param = $request->input();
        $userId = $request->user()->id;

        $codeDep = new SubCodeDep();
        $resCode = $codeDep->firstByCode($param['code']);
        if (!$resCode) {
            return self::response([], '请输入正确的邀请码', 100);
        }

        if (date('Y-m-d H:i:s') > $resCode->expire_at) {
            return self::response([], '邀请码已过期', 100);
        }

        if ($resCode->status == SubCodeEnum::STATUS_USED) {
            return self::response([], '邀请码已被使用', 100);
        }

        $data = [
            'status' => SubCodeEnum::STATUS_USED,
            'user_id' => $userId
        ];

        $codeDep->upd($resCode->id, $data);

        $subTeamUserDep = new SubTeamUserDep();
        $resJoin = $subTeamUserDep->firstByTeamUser($resCode->team_id, $userId);
        if ($resJoin) {
            return self::response([], '已加入工会，请勿重复加入', 100);
        }

        $data = [
            'user_id' => $userId,
            'team_id' => $resCode->team_id
        ];

        $subTeamUserDep->add($data);

        return self::response();

    }

}

